package tech.lixinlei.collection.list.remove;

import com.alibaba.fastjson.JSONObject;
import tech.lixinlei.collection.list.remove.bo.Apple;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class RemoveDemo2 {

    public static void main(String[] args) {
        List<Apple> apples = prepareData();

        Apple a = new Apple();
        a.setColor("green");
        a.setId(2);

        iteratorRemove(apples);

        print(apples);
    }

    private static void iteratorRemove(List<Apple> apples) {
        Iterator<Apple> it = apples.iterator();
        while (it.hasNext()) {
            Apple apple = it.next();
            if (apple.getColor().equals("green")) {
                it.remove();
            }
        }
    }

    private static void currentModificationException(List<Apple> apples) {
        for (Apple apple : apples) {
            if (apple.getColor().equals("green")) {
                apples.remove(apple);
            }
        }
    }

    private static void print(List<Apple> apples) {
        System.out.println();
        for (Apple a : apples) {
            System.out.println(JSONObject.toJSONString(a));
        }
    }

    private static List<Apple> prepareData() {
        List<Apple> apples = new ArrayList<>();

        Apple a1 = new Apple();
        a1.setColor("red");
        a1.setId(1);
        apples.add(a1);

        Apple a2 = new Apple();
        a2.setId(2);
        a2.setColor("green");
        apples.add(a2);

        Apple a3 = new Apple();
        a3.setId(3);
        a3.setColor("orange");
        apples.add(a3);

        print(apples);

        return apples;
    }

}
